package com.top10.controller;

import com.allinpay.syb.QpayConstants;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.top10.bean.JwtUtil;
import com.top10.bean.ResponseBean;
import com.top10.common.AliPayConst;
import com.top10.entity.*;
import com.top10.entity.TL.AgreeApply;
import com.top10.entity.TL.AgreeConfirm;
import com.top10.entity.vo.UserCartGoodsVo;
import com.top10.service.*;
import com.top10.utils.GetUuid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/tlzf")
public class TLController {

    private static final Logger logger = LoggerFactory.getLogger("system");

    @Autowired
    IUserService userService;
    @Autowired
    IOrderDetailedService iOrderDetailedService;
    @Autowired
    IUserAgreeidService iUserAgreeidService;
    @Autowired
    IOrderService orderService;
    @Autowired
    IUserDepositService userDepositService;
    @Autowired
    IUserCartService userCartService;
    @Autowired
    private IGoodsDetailedService iGoodsDetailedService;


    /**
     * 协议申请
     *
     * @return
     */
    @RequestMapping("/manager/agreeapply")
    public ResponseBean agreeApply(HttpServletRequest request, AgreeApply agreeApply) throws Exception {
        Map<String, String> params = buildBasicMap();
        String uuid = JwtUtil.getUuidByToken(request);
        params.put("meruserid", uuid);//可以随便传
        params.put("accttype", agreeApply.getAccttype());//卡类型
        params.put("acctno", agreeApply.getAcctno());
        params.put("idno", agreeApply.getIdno());
        params.put("acctname", agreeApply.getAcctname());
        params.put("mobile", agreeApply.getMobile());
        if (agreeApply.getCvv2() != null) {
            params.put("cvv2", agreeApply.getCvv2());
        }
        if (agreeApply.getValiddate() != null) {
            params.put("validdate", agreeApply.getValiddate());
        }

        Map<String, String> map = com.allinpay.syb.QpayUtil.
                dorequest(
                        QpayConstants.SYB_APIURL_QPAY + "/agreeapply",
                        params, QpayConstants.SYB_APPKEY);
        return ResponseBean.createSuccess().addData("map", map);
    }

    /**
     * 协议申请确认
     *
     * @return
     */
    @RequestMapping("/manager/agreeconfirm")
    public ResponseBean agreeConfirm(HttpServletRequest request, AgreeConfirm agreeConfirm) throws Exception {
        Map<String, String> params = buildBasicMap();
        String uuid = JwtUtil.getUuidByToken(request);
        params.put("meruserid", uuid);//可以随便传
        params.put("accttype", agreeConfirm.getAccttype());//卡类型
        params.put("acctno", agreeConfirm.getAcctno());
        params.put("idno", agreeConfirm.getIdno());
        params.put("acctname", agreeConfirm.getAcctname());
        params.put("mobile", agreeConfirm.getMobile());
        if (agreeConfirm.getCvv2() != null) {
            params.put("cvv2", agreeConfirm.getCvv2());
        }
        if (agreeConfirm.getValiddate() != null) {
            params.put("validdate", agreeConfirm.getValiddate());//信用卡上有的
        }
        if (agreeConfirm.getThpinfo() != null) {
            params.put("thpinfo", agreeConfirm.getThpinfo());//协议申请返回
        }
        params.put("smscode", agreeConfirm.getSmscode());//短信验证码
        Map<String, String> map = com.allinpay.syb.QpayUtil.dorequest(QpayConstants.SYB_APIURL_QPAY + "/agreeconfirm", params, QpayConstants.SYB_APPKEY);
        return ResponseBean.createSuccess().addData("map", map);
    }

    /**
     * 存储协议编码
     *
     * @param request
     * @param agreeid
     * @return
     * @throws Exception
     */

    @RequestMapping("/manager/getagreeid")
    public ResponseBean getAgreeid(HttpServletRequest request, String agreeid) throws Exception {
        String uuid = JwtUtil.getUuidByToken(request);
        UserAgreeid userAgreeid = new UserAgreeid();
        userAgreeid.setId(new GetUuid().newId());
        userAgreeid.setAgreeid(agreeid);
        userAgreeid.setUserUuid(uuid);
        Integer rest = iUserAgreeidService.insertAgreeid(userAgreeid);
        if (rest != 0) {
            return ResponseBean.createSuccess("存储成功");
        }
        return ResponseBean.createError("存储失败");
    }

    /**
     * 支付申请
     *
     * @param request
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/manager/payapply")
    public ResponseBean payApply(HttpServletRequest request, String payid, Long type) throws Exception {
        if (type == null || "".equals(type)) {
            return ResponseBean.createError("支付类型不能为空");
        }


        double actualPrice = 0;
        if (type == 1) {
            if (payid == null || "".equals(payid)) {
                return ResponseBean.createError("订单号不能为空");
            }

            List<Order> orders = orderService.selectList(new EntityWrapper<Order>().eq("payid", payid));
            if (orders == null) {
                return ResponseBean.createError("不存在该订单，支付发生错误");
            }

            for (Order order : orders) {
                actualPrice += order.getActualPrice();
            }
        }


        if (type == 2) {

            if (payid == null || "".equals(payid)) {
                return ResponseBean.createError("充值订单号不能为空");
            }

            UserDeposit userDeposit = userDepositService.selectOne(new EntityWrapper<UserDeposit>().eq("order_sn", payid));
            if (userDeposit == null) {
                return ResponseBean.createError("不存在该信息，充值发生错误");
            }
            actualPrice = userDeposit.getMoney().doubleValue();
        }


        String userUuid = JwtUtil.getUuidByToken(request);
        UserAgreeid userAgreeid = iUserAgreeidService.selectOne(new EntityWrapper<UserAgreeid>().eq("user_uuid", userUuid));


        int actualPrice1 = (int) (actualPrice * 100);
        String actualPrice2 = String.valueOf(actualPrice1);
        Map<String, String> params = buildBasicMap();
        params.put("orderid", payid);
        params.put("amount", actualPrice2);///订单金额
        params.put("subject", "顶十商城");//备注
        params.put("notifyurl", "http://112.74.208.66:8999/top10-app/tlzf/tlnotify.action");//回调地址
        params.put("currency", "CNY");
        params.put("agreeid", userAgreeid.getAgreeid());//绑卡返回的agreeid
        Map<String, String> map = com.allinpay.syb.QpayUtil.dorequest(QpayConstants.SYB_APIURL_QPAY + "/payapplyagree", params, QpayConstants.SYB_APPKEY);
        return ResponseBean.createSuccess().addData("map", map);
    }

    /**
     * 支付申请确认
     *
     * @return
     */

    @RequestMapping("/manager/pay")
    public ResponseBean Pay(HttpServletRequest request, String thpinfo, String payid, String smscode) throws Exception {
        String userUuid = JwtUtil.getUuidByToken(request);
        UserAgreeid userAgreeid = iUserAgreeidService.selectOne(new EntityWrapper<UserAgreeid>().eq("user_uuid", userUuid));
        Map<String, String> params = buildBasicMap();
        params.put("orderid", payid);//payapply的单号
        params.put("agreeid", userAgreeid.getAgreeid());//绑卡返回的agreeid
        params.put("smscode", smscode);//短信验证码
        if (thpinfo != null) {
            params.put("thpinfo", thpinfo);
        }
        Map<String, String> map = com.allinpay.syb.QpayUtil.dorequest(QpayConstants.SYB_APIURL_QPAY + "/payagreeconfirm", params, QpayConstants.SYB_APPKEY);
        return ResponseBean.createSuccess().addData("map", map);
    }

    /**
     * 回调地址异步通知
     *
     * @return
     */
    @RequestMapping(value = "/tlnotify", method = RequestMethod.POST)
    public void alipayCallback(HttpServletRequest request) {

        Map<String, String> paramsone = new HashMap<>();
        Map requestParams = request.getParameterMap();


        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {

                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            paramsone.put(name, valueStr);
        }
        if (paramsone != null) {
            Long cusorderid = Long.parseLong(paramsone.get("cusorderid"));
            List<Order> orders = orderService.selectList(new EntityWrapper<Order>().eq("payid", cusorderid));
            if (orders != null) {
                for (Order order : orders) {
                    //修改该订单状态为 ：待发货
                    order.setStatus(AliPayConst.ORDER_WAIT_STATUS);
                    //旧的状态为待支付
                    order.setOldStatus(7);
                    order.setUpdatetime(new Date());
                    orderService.updateById(order);
                    //购物车清理的问题
                    UserCartGoodsVo goods=iOrderDetailedService.selectGoods(order.getId());
                    if(goods!=null){
                        if(goods.getAttributes().equals("{}") || goods.getAttributes()==null){
                            userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",order.getUserUuid()).eq("goods_uuid",goods.getGoods_uuid()).eq("isdeleted",false));
                        }else{
                            userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",order.getUserUuid()).eq("goods_uuid",goods.getGoods_uuid()).eq("attributes",goods.getAttributes()).eq("ideleted",false));
                        }
                    }

                    //销量增加
                    List<OrderDetailed> orderDetailedsLists=iOrderDetailedService.selectList(new EntityWrapper<OrderDetailed>().eq("order_uuid",order.getUuid()));
                    for(OrderDetailed orderDetailedList:orderDetailedsLists) {
                        GoodsDetailed goodsDetailed = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("uuid", orderDetailedList.getGoodsDetailedUuid()));
                        goodsDetailed.setSoldQuantity(goodsDetailed.getSoldQuantity()+orderDetailedList.getQuantity());
                        iGoodsDetailedService.updateById(goodsDetailed);
                    }

                }
            }
            UserDeposit userDeposit=userDepositService.selectOne(new EntityWrapper<UserDeposit>().eq("order_sn",cusorderid));
            User user=userService.selectOne(new EntityWrapper<User>().eq("uuid",userDeposit.getUid()));
            user.setMoney(user.getMoney().add(userDeposit.getMoney()));
            userDeposit.setOrderStatus(1);
            userDeposit.setTradeTime(new Date());
            userDepositService.updateById(userDeposit);
            userService.updateById(user);
        }
    }
  /*  *
     * 退款申请
     * @return

    @RequestMapping("/refund")
    public ResponseBean Refund(){ return null;}
*/

    public static Map<String, String> buildBasicMap() {
        TreeMap<String, String> params = new TreeMap<String, String>();
        params.put("appid", QpayConstants.SYB_APPID);
        params.put("cusid", QpayConstants.SYB_CUSID);
        params.put("version", "11");
        params.put("randomstr", System.currentTimeMillis() + "");
        return params;
    }

}
